Difference between public, private, and protected inheritance in C++?
Difference between public, private, and protected inheritance in C++?
631
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023In C++, inheritance is a mechanism that allows a new class to inherit the properties and behavior of an existing class. The three types of inheritance are public, private, and protected.
The type of inheritance that you use will depend on the specific needs of your application. If you want the derived class to have full access to the members of the base class, then you should use public inheritance. If you want to restrict access to the members of the base class, then you should use private or protected inheritance.
Here is an example of how to use public inheritance:
C++
In this example, the
Derivedclass inherits from theBaseclass using public inheritance. This means that all the members of theBaseclass are public in theDerivedclass. Therefore, theDerivedclass can access thexvariable and theprint()method from theBaseclass.Here is an example of how to use private inheritance:
C++
In this example, the
Derivedclass inherits from theBaseclass using private inheritance. This means that all the members of theBaseclass are private in theDerivedclass. Therefore, theDerivedclass cannot access thexvariable or theprint()method from theBaseclass.Here is an example of how to use protected inheritance:
C++
In this example, the
Derivedclass inherits from theBaseclass using protected inheritance. This means that all the members of theBaseclass are protected in theDerivedclass. Therefore, theDerivedclass can access thexvariable and theprint()method from theBaseclass, but only from within theDerivedclass or from any class that is derived from theDerivedclass.